<?php
function searchelement() {
  global $_GET, $path, $style, $header;
  include "class.php";
  if (is_numeric($_GET["uid"])){
    // search in ontologies...
    $filename = $path[$style]["tpl"]."/action.xml";
    $fp = fopen($filename, "r");
    $contents = fread($fp, filesize ($filename));
    fclose ($fp);
    preg_match("/\%REPEAT\%(.*?)\%REPEAT\%/s", $contents, $matches);
    
    $sql = "SELECT o.id FROM ontology o, term t WHERE o.term_id = t.id and t.text LIKE '%".$_GET["sst"]."%' ORDER BY t.text, o.id";
    $i_max = getMultdata($sql, $onto_id);
    if ($i_max > 0){
      $i = 0;
      while (($onto_id[$i]["id"] != $_GET["uid"]) && ($i <= $i_max)){
        $i++;
      };
      if ($onto_id[$i]["id"] == $_GET["uid"])
        if ($i + 1 < $i_max)
          $index = $i + 1;
        else
          $index = 0;
      else
        $index = 0;
      $contents = str_replace($matches[0], $rep_cont, $contents);
      $contents = str_replace("%SELECT%", $onto_id[$index]["id"], $contents);
      $contents = str_replace("%SCCSS%", "1", $contents);
      $contents = str_replace("%ACT_ID%", "Select", $contents);
    }else{
      $contents = str_replace($matches[0], $rep_cont, $contents);
      $contents = str_replace("%SCCSS%", "0", $contents);
    };
      
    header ($header["xml"]);
    return $contents;
    
  }else{
    // search in current ontology
    $i = 1;
    $class_id = 0;
    // determine class id from identificator (like "c4954")
    while ($i < strlen($_GET["uid"]) && ($class_id == 0)){
      if (is_numeric(substr($_GET["uid"], $i, strlen($_GET["uid"])))){
        $class_id = substr($_GET["uid"], $i, strlen($_GET["uid"]));
      };
      $i++;
    };
    $sql = "SELECT c.id, c.onto_id FROM class c, term t WHERE c.term_id=t.id and t.text LIKE '%".$_GET["sst"]."%' and c.onto_id = (SELECT onto_id from class WHERE id=".$class_id.") ORDER BY c.parent_id, t.text";
    $i_max = getMultdata($sql, $looked_class_id);
    if ($i_max > 0){
      $i = 0;
      while (($looked_class_id[$i]["id"] != $class_id) && ($i <= $i_max)){
        $i++;
      };
      if ($looked_class_id[$i]["id"] == $class_id)
        if ($i + 1 < $i_max)
          $index = $i + 1;
        else
          $index = 0;
      else
        $index = 0;
      // select looked class
      $_GET["uid"] = $looked_class_id[$index]["onto_id"];
      return taxonomy(1, $looked_class_id[$index]["id"]);
    }else{
      // select Thing
      $sql = "SELECT id, onto_id FROM class WHERE parent_id = 0 and onto_id = (SELECT onto_id FROM class WHERE id = ".$class_id.")";
      getdata($sql, $class_id);
      $_GET["uid"] = $class_id["onto_id"];
      return taxonomy(1, $class_id["id"]);
    }
  };
}
?>
